<?php

// @formatter:off
/**
 * @file WCEComicsRepository.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: WCEComicsRepository.php 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/extensions/Repositories/includes/WCEComicsRepository.php $
 */
class WCEComicsRepository extends WCERepository {
	//
	// Public methods.
	/**
	 * @return WCDirectory
	 */
	public function balancer() {
		$balancerDir = false;

		$this->loadDirectories();

		$directories = $this->directories();
		uasort($directories, "WCDirectory::NameSort");
		foreach($directories as $dir) {
			if($dir->count < WC_E_REPOSITORIES_MAX) {
				$balancerDir = $dir;
				break;
			}
		}

		return $balancerDir;
	}
	//
	// Protected methods.
	protected function checkBalance() {
		if(!$this->_flags["checkBalance"]) {
			$this->_balanced = true;

			if($this->_mainDirectory->count > 0) {
				$this->_balanced = false;
				$this->_badDirectory = $this->_mainDirectory;
				$this->_correctionSize = 0;
			} else {
				$directories = $this->directories();
				uasort($directories, "WCDirectory::NameSort");

				$prevCount = WC_E_REPOSITORIES_MAX;
				foreach($directories as $dir) {
					$c = $dir->count;
					if($c > WC_E_REPOSITORIES_MAX) {
						$this->_balanced = false;
						$this->_badDirectory = $dir;
						$this->_correctionSize = WC_E_REPOSITORIES_MAX;
						break;
					} elseif($c > $prevCount) {
						$this->_balanced = false;
						$this->_badDirectory = $dir;
						$this->_correctionSize = $prevCount < WC_E_REPOSITORIES_MAX ? $c - (WC_E_REPOSITORIES_MAX - $prevCount) : WC_E_REPOSITORIES_MAX;
						break;
					} elseif($c < WC_E_REPOSITORIES_MAX) {
						if($prevCount < WC_E_REPOSITORIES_MAX && $c != 0) {
							$nomads = WC_E_REPOSITORIES_MAX - $prevCount;

							$this->_balanced = false;
							$this->_badDirectory = $dir;
							$this->_correctionSize = $nomads > $c ? 0 : $c - $nomads;
							break;
						}
					}

					$prevCount = $dir->count;
				}
			}

			$this->_flags["checkBalance"] = true;
		}
	}
	//
	// Public class methods.
	/**
	 * This class method allows to get the sole instance of this holder.
	 *
	 * @param WCGroup $group Instance filter.
	 * @return WCERepository Returns the singleton instance of this
	 * class.
	 */
	public static function Instance(WCGroup &$group) {
		//
		// Checking if there's no instance yet.
		if(!isset(self::$_Instance["cmc"][$group->id])) {
			$c = __CLASS__;
			if(!isset(self::$_Instance["cmc"])) {
				self::$_Instance["cmc"] = array();
			}
			//
			// Creating the sole instance.
			self::$_Instance["cmc"][$group->id] = new $c($group);
		}
		//
		// Returning the class instance.
		return self::$_Instance["cmc"][$group->id];
	}
}
